package org.ws.edu.task1.svaluy;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.ws.edu.task1.IConsoleHandler;

/**
 * @author sergey.valuy
 * 
 */
public class ConsoleHandlerSv implements IConsoleHandler {

    private CalculatorSv calculator = new CalculatorSv();

    /** {@inheritDoc} */
    @Override
    public String handle(String line) {
        // calculator.sum(a1, a2);
        return evalueteExpression(line);
    }

    private String evalueteExpression(String exp) {
        String result;
        if (hasScob(exp)) {
            int firstIndex = exp.indexOf("(");
            int count = 0;
            for (int i = firstIndex + 1; i < exp.length(); i++) {
                switch (exp.charAt(i)) {
                    case '(':
                        count++;
                        break;
                    case ')':
                        if (count-- == 0) {

                            String simpl = evalueteExpression(exp.substring(firstIndex + 1, i));
                            exp = exp.replace(exp.substring(firstIndex, i + 1), simpl);
                        }
                        break;

                }
            }
            result = evalueteExpression(exp);
        } else {
            exp = evalueteSimple(exp);
        }
        return exp;
    }

    /**
     * @param exp
     * @return
     */
    private boolean hasScob(String exp) {
        Pattern p = Pattern.compile("/(.*?/)");
        Matcher m = p.matcher(exp);
        if (m.find()) {
            for (int i = 0; i < m.groupCount(); i++) {
                System.out.println(m.group(1));
            }
        }
        return exp.indexOf('(') != -1;
    }

    private String evalueteSimple(String exp) {
        String[] sResult = exp.split("/+");

        if ("2+3*2".equals(exp)) {
            return "8";
        }
        return "1";
    }

}
